import 'package:card_swiper/card_swiper.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:wan_android/model/fav/fav_page_model.dart';
import 'package:wan_android/model/home/home_article_type.dart';
import 'package:wan_android/model/home/home_page_model.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:wan_android/model/user/user_page_model.dart';
import 'package:wan_android/pages/login_dialog/login_dialog.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final RefreshController _refreshController = RefreshController();
  final ScrollController _customScrollController = ScrollController();

  late UserPageModel _userPageModel;
  late HomePageModel _homePageModel;
  late FavPageModel _favPageModel;

  bool isShowTitle = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    UserPageModel userPageModel = Provider.of<UserPageModel>(context, listen: false);
    userPageModel.getStorageInfo();

    HomePageModel homePageModel = Provider.of<HomePageModel>(context, listen: false);
    homePageModel.getBanner();
    homePageModel.getArticle(false);

    FavPageModel favPageModel = Provider.of<FavPageModel>(context, listen: false);

    setState(() {
      _userPageModel = userPageModel;
      _homePageModel = homePageModel;
      _favPageModel = favPageModel;
    });

    _customScrollController.addListener(_handlerScroll);
  }

  _handlerScroll() {
    // print('滚动到了${_customScrollController.offset}');

    bool isShow = false;
    if (_customScrollController.offset > 150) {
      isShow = true;
    } else {
      isShow = false;
    }
    setState(() {
      isShowTitle = isShow;
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _customScrollController.dispose();
    _refreshController.dispose();
  }

  Widget _banner() {
    return Consumer<HomePageModel>(
      builder: (context, vm, child) {
        return SizedBox(
          width: double.infinity,
          height: 400.h,
          child: Swiper(
            itemCount: vm.bannerList.length,
            itemBuilder: (context, index) {
              return InkWell(
                onTap: () {
                  print(123);
                },
                child: Image.network(
                  vm.bannerList[index].imagePath,
                  fit: BoxFit.cover,
                )
              );
            }
          ),
        );
      },
    );
  }

  _showLoginDialog(ArticleItemData row) async {
    // 判断是否登录过，未登录弹窗进行登录
    if (_userPageModel.userInfo != null) {
      // 收藏
      if (!row.collect) {
        bool res = await _favPageModel.setFavArticle(row.id);
        if (res) {
          row.collect = true;
          _userPageModel.addFav(row.id);
        }
        return;
      }

      // 取消收藏
      if (row.collect) {
        bool res = await _favPageModel.cancelFavArticle(row.id);
        if (res) {
          row.collect = false;
          _userPageModel.removeFav(row.id);
        }
        return;
      }
      return;
    }
    // showCupertinoDialog(
    //   context: context,
    //   builder: (context) => const LoginDialog()
    // );
    bool res = await LoginDialog.showLoginDialog(context);
    if (res) {
      final refresh = await context.push('/login');

      if (refresh != null && refresh as bool) {
        print('刷新接口====== dev001');
        await _homePageModel.getBanner();
        await _homePageModel.getArticle(false);
        _customScrollController.animateTo(0, duration: const Duration(milliseconds: 200), curve: Curves.linear);
      }
    }
  }

  Widget _articleLists() {
    return  Consumer<HomePageModel>(
      builder: (context, vm, child) {
        
        return SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, index) {
              DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(vm.articleList[index].shareDate);
              String date = '${dateTime.year}-${dateTime.month}-${dateTime.day} ${dateTime.hour}:${dateTime.minute}:${dateTime.second}';

              return InkWell(
                onTap: () {
                  context.push('/webview?url=${vm.articleList[index].link}');
                },
                child: Container(
                  width: double.infinity,
                  padding: EdgeInsets.symmetric(vertical: 20.h, horizontal: 40.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              const Icon(Icons.person),
                              Text(vm.articleList[index].author),
                            ],
                          ),
                          Text(date, style: const TextStyle(fontWeight: FontWeight.bold),)
                        ]
                      ),
                      
                      Padding(
                        padding: EdgeInsets.symmetric(vertical: 10.h, horizontal: 10.w),
                        child: Text(vm.articleList[index].title),
                      ),

                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              Text(vm.articleList[index].superChapterName.toString()),
                              Icon(Icons.circle, size: 10.sp,),
                              Text(vm.articleList[index].chapterName),
                            ],
                          ),
                          // IconButton(
                          //   icon: Icon(vm.articleList[index].collect ? Icons.favorite_outlined : Icons.favorite_border, color: Colors.redAccent),
                          //   onPressed: () {
                          //     _showLoginDialog(vm.articleList[index]);
                          //   },
                          // ),

                          Consumer<UserPageModel>(
                            builder: (context, userVM, child) {
                              if (userVM.userInfo == null) {
                                return IconButton(
                                  icon: const Icon(Icons.favorite_border, color: Colors.redAccent),
                                  onPressed: () {
                                    _showLoginDialog(vm.articleList[index]);
                                  },
                                );
                              }

                              return IconButton(
                                icon: Icon(userVM.userInfo!.collectIds.contains(vm.articleList[index].id) ? Icons.favorite_outlined : Icons.favorite_border, color: Colors.redAccent),
                                onPressed: () {
                                  _showLoginDialog(vm.articleList[index]);
                                },
                              );
                            },
                          )
                        ],
                      )
                    ],
                  ),
                ),
              );
            },
            childCount: vm.articleList.length,
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      top: false,
      child: Scaffold(
        body: SmartRefresher(
          controller: _refreshController,
          enablePullDown: true,
          enablePullUp: true,
          header: const ClassicHeader(),
          footer: const ClassicFooter(),
          onRefresh: () async {
            await _homePageModel.getBanner();
            await _homePageModel.getArticle(false);
            _refreshController.refreshCompleted();
          },
          onLoading: () async {
            await _homePageModel.getArticle(true);
            // _refreshController.refreshCompleted();
            _refreshController.loadComplete();
          },
          child: CustomScrollView(
            controller: _customScrollController,
            slivers: [
              SliverAppBar(
                pinned: true, // 如果为 true，应用栏将在滚动时固定在顶部
                snap: false, // 如果为 true，并且 floating 为 true，应用栏将在用户停止滚动时立即展开
                floating: false, // 如果为 true，应用栏将在用户向下滚动时立即显示，而不是等到滚动到顶部
                expandedHeight: 400.h,
                backgroundColor: Colors.blueAccent,
                actions: [
                  InkWell(
                    child: const Icon(Icons.search),
                    onTap: () {
                      context.push('/search');
                      // context.go('/search');
                    },
                  )
                ],
                title: AnimatedDefaultTextStyle(
                  duration: const Duration(milliseconds: 300), 
                  style: TextStyle(fontSize: isShowTitle ? 48.sp : 0.sp),
                  child: const Text( '首页', style: TextStyle(color: Colors.white)),
                ),
                centerTitle: true,
                flexibleSpace: FlexibleSpaceBar(
                  background: _banner(),
                  centerTitle: true,
                ),
              ),

              _articleLists()
            ],
          )
        ),
      ),
    );
  }
}
